// https://ask.dcloud.net.cn/article/39120
// https://blog.csdn.net/qq_45963071/article/details/134858710

let File = plus.android.importClass("java.io.File");
let BufferedReader = plus.android.importClass("java.io.BufferedReader");
let FileReader = plus.android.importClass("java.io.FileReader");
let FileWriter = plus.android.importClass("java.io.FileWriter");
var appName = "AccountBook";
var basePath = "/storage/emulated/0/Download";
// 写文件
export const createNewFile = (filename, res) => {
	res = res ? JSON.stringify(res) : ''; //对象转换为json文本  
	try {
		let directory = new File(basePath, appName); //文件夹
		if (!directory.exists()) {
			directory.mkdirs(); //不存在创建目录  
		}
		let file = new File(basePath + "/" + appName, filename); //文件
		if (file.exists()) {
			file.delete()
		}
		file.createNewFile(); //创建文件  
		let fos = new FileWriter(file, false);
		fos.write(res);
		fos.close();
		return true;
	} catch (e) {
		return false;
	}
	return false;
};
export const readFileData = (fileName) => {
	let readFr = new File(fileName);
	return new Promise((resolve, reject) => {
		try {  
			let reader = new BufferedReader(new FileReader(readFr));  
			let txt;  
			let retxt = '';  
			while (true) {  
				txt = reader.readLine(); //读取文件  
				if (txt == null) {  
					break;  
				}  
				retxt = retxt + '\r\n' + txt;  
			}  
			resolve(retxt)
		} catch (e) {  
			reject(e)
		} 
	})
}
// 获得文件路径
export const openFileTool = () => {
	let main = plus.android.runtimeMainActivity();
	let Intent = plus.android.importClass("android.content.Intent");
	let fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
	fileIntent.setType("*/*"); //无类型限制
	fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
	main.startActivityForResult(fileIntent, 1);
	// 返回路径
	var path = "";
	return new Promise((resolve, reject) => {

		// 获取回调
		main.onActivityResult = function(requestCode, resultCode, data) {
			let Activity = plus.android.importClass("android.app.Activity");
			let ContentUris = plus.android.importClass("android.content.ContentUris");
			let Cursor = plus.android.importClass("android.database.Cursor");
			let Uri = plus.android.importClass("android.net.Uri");
			let Build = plus.android.importClass("android.os.Build");
			let Environment = plus.android.importClass("android.os.Environment");
			let DocumentsContract = plus.android.importClass(
				"android.provider.DocumentsContract"
			);
			let MediaStore = plus.android.importClass("android.provider.MediaStore");

			// 给系统导入 contentResolver
			let contentResolver = main.getContentResolver();
			plus.android.importClass(contentResolver);
			if (resultCode == Activity.RESULT_OK) {
				let uri = data.getData();
				let src = uri.getPath();
				let source = new File(src);
				// 获取文件相关信息

				if ("file" == uri.getScheme().toLowerCase()) {
					//使用第三方应用打开
					path = uri.getPath();
					return;
				}
				if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
					//4.4以后
					path = getPath(this, uri);

				} else {
					//4.4以下下系统调用方法
					path = getRealPathFromURI(uri);
				}
				if (path != "") resolve(path)
			} else {
				reject(false)
			}
			// 4.4 以上 从Uri 获取文件绝对路径
			function getPath(context, uri) {
				let isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
				let scheme = uri.getScheme().toLowerCase();
				if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
					// ExternalStorageProvider
					if (isExternalStorageDocument(uri)) {
						let docId = DocumentsContract.getDocumentId(uri);
						let split = docId.split(":");
						let type = split[0];
						// 如果是手机内部存储
						if ("primary" == type.toLowerCase()) {
							return Environment.getExternalStorageDirectory() + "/" + split[1];
						} else {
							return "/storage/" + type + "/" + split[1];
						}
					}
					// DownloadsProvider
					else if (isDownloadsDocument(uri)) {
						let id = DocumentsContract.getDocumentId(uri);
						let split = id.split(":");
						let contentUri = ContentUris.withAppendedId(Uri.parse(
							"content://downloads/public_downloads"), id);
						return getDataColumn(context, uri, null, null);
					}
					// MediaProvider
					else if (isMediaDocument(uri)) {
						let docId = DocumentsContract.getDocumentId(uri);
						let split = docId.split(":");
						let type = split[0];
						let contentUri = null;
						if ("image" == type.toLowerCase()) {
							contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
						} else if ("video" == type.toLowerCase()) {
							contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
						} else if ("audio" == type.toLowerCase()) {
							contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
						}
						let selection = "_id=?";
						let selectionArgs = [split[1]];
						return getDataColumn(context, contentUri, selection, selectionArgs);
					}
				}
				// MediaStore (and general)
				else if ("content" == scheme) {
					return getDataColumn(context, uri, null, null);
				}
				// File
				else if ("file" == scheme) {
					return uri.getPath();
				}
			}
			// 4.4 以下 获取 绝对路径
			function getRealPathFromURI(uri) {
				let res = null;
				let proj = [MediaStore.Images.Media.DATA];
				let cursor = contentResolver.query(uri, proj, null, null, null);
				if (null != cursor && cursor.moveToFirst()) {
					let column_index = cursor.getColumnIndexOrThrow(
						MediaStore.Images.Media.DATA
					);
					res = cursor.getString(column_index);
					cursor.close();
				}
				return res;
			}
			// 通过uri 查找出绝对路径
			function getDataColumn(context, uri, selection, selectionArgs) {
				let cursor = null;
				let column = "_data";
				let projection = [column];
				cursor = contentResolver.query(
					uri,
					projection,
					selection,
					selectionArgs,
					null
				);
				if (cursor != null && cursor.moveToFirst()) {
					let column_index = cursor.getColumnIndexOrThrow(column);
					return cursor.getString(column_index);
				} else {
					cursor.close()
					return null
				}
			}

			function isExternalStorageDocument(uri) {
				return "com.android.externalstorage.documents" == uri.getAuthority() ?
					true :
					false;
			}

			function isDownloadsDocument(uri) {
				return "com.android.providers.downloads.documents" == uri.getAuthority() ?
					true :
					false;
			}

			function isMediaDocument(uri) {
				return "com.android.providers.media.documents" == uri.getAuthority() ?
					true :
					false;
			}
		};
	});
}